package com.medical.service.impl;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.medical.dao.AuthenticationCashMapper;
import com.medical.dao.AuthenticationCertificateMapper;
import com.medical.dao.AuthenticationLanguageMapper;
import com.medical.dao.AuthenticationSchoolMapper;
import com.medical.dao.AuthenticationStudyingMapper;
import com.medical.dao.CollectMapper;
import com.medical.dao.TeacherAuthenticationMapper;
import com.medical.dao.TeacherAuthenticationcreditMapper;
import com.medical.dao.TeacherMapper;
import com.medical.dao.TeacherOrderMapper;
import com.medical.dao.UserMapper;
import com.medical.entity.Collect;
import com.medical.entity.MyException;
import com.medical.entity.ResultBean;
import com.medical.entity.Teacher;
import com.medical.entity.TeacherAuthentication;
import com.medical.entity.User;
import com.medical.service.TeacherService;
import com.medical.util.DataUtil;
import com.medical.util.LocationUtils;

@Service
@Transactional
public class TeacherSerivceImpl implements TeacherService {
	@Autowired
	private TeacherMapper dao;
	
	@Resource
	private TeacherAuthenticationMapper tDao;
	
	@Resource
	private UserMapper uDao;
	
	@Resource
	private CollectMapper cDao;
	
	@Resource
	private AuthenticationCertificateMapper acfDao;
	
	@Resource
	private AuthenticationLanguageMapper aclDao;
	
	@Resource
	private AuthenticationSchoolMapper acsDao;
	
	@Resource
	private AuthenticationStudyingMapper asDao;
	
	@Resource
	private TeacherAuthenticationcreditMapper tacDao;
	
	@Resource
	private AuthenticationCashMapper acDao;
	
	@Resource
	private TeacherOrderMapper toDao;
	
	@Override
	public ResultBean<Integer> addTeacher(Teacher tea) {
		// TODO Auto-generated method stub
		try {
			TeacherAuthentication ta=tDao.getByUserid(tea.getUserid());
			if(ta==null) {
				return new ResultBean<>(new MyException("未认证"));
			}
			if(ta.getStates()!=2) {
				return new ResultBean<>(new MyException("认证未通过"));
			}
			tea.setTime(new Date());
			tea.setStates(1);
			tea.setRelease(true);
			int count=dao.insert(tea);
			if(count>0) {
				return new ResultBean<>(tea.getId());
			}else {
				return new ResultBean<>(new MyException("添加异常"));
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return new ResultBean<>(new MyException("系统异常"));
		}
	}

	@Override
	public ResultBean<List<Map<String, Object>>> selectByTeacher(Teacher tea,String ages,String teachings,Double minprice,Double maxprice, int score, String nationality,Integer pageIndex,Integer size,Double longitude,Double latitude,String keyword) {
		// TODO Auto-generated method stub
		StringBuffer whereSql=new StringBuffer(" where 1=1 and t.name like '%"+keyword+"%'");
		if(tea.getLanguageid()!=null&&tea.getLanguageid()!=0) {
			whereSql.append(" and t.languageid="+tea.getLanguageid());
		}
		if(minprice!=null&&maxprice!=0.0) {
			whereSql.append(" and t.price>="+minprice+" and t.price<="+maxprice);
		}
		if(ages!=null&&!ages.equals("")) {
			String[] age=ages.split("-");
			whereSql.append(" and (DATE_FORMAT(FROM_DAYS(TO_DAYS(NOW())-TO_DAYS(ta.birthdate)), '%Y')+0)>="+age[0]+" and (DATE_FORMAT(FROM_DAYS(TO_DAYS(NOW())-TO_DAYS(ta.birthdate)), '%Y')+0)<="+age[1]);
		}
		if(teachings!=null&&!teachings.equals("")) {
			String[] teaching=teachings.split("-");
			whereSql.append(" and t.teaching>="+teaching[0]+" and t.teaching<="+teaching[1]);
		}
		if(tea.getPrice()!=null&&tea.getPrice()!=0) {
			whereSql.append(" and i.intolanguage="+tea.getPrice());
		}
		if(tea.getLanguagegrade()!=null&&!tea.getLanguagegrade().equals("")) {
			whereSql.append(" and t.languagegrade='"+tea.getLanguagegrade()+"'");
		}
		if(tea.getAddress()!=null&&!tea.getAddress().equals("")) {
			whereSql.append(" and t.address like '%"+tea.getAddress()+"%'");
		}
		if(tea.getHauptstudiumid()!=null&&!tea.getHauptstudiumid().equals("")) {
			whereSql.append(" and t.hauptstudiumid='"+tea.getHauptstudiumid()+"'");
		}
		if(tea.getExperience()!=null&&!tea.getExperience().equals("")) {
			whereSql.append(" and t.experience="+tea.getExperience());
		}
		if(tea.getEducation()!=null&&!tea.getEducation().equals("")) {
			whereSql.append(" and t.education='"+tea.getEducation()+"'");
		}
		if(tea.getCertificate()!=null&&!tea.getCertificate().equals("")) {
			whereSql.append(" and t.certificate='"+tea.getCertificate()+"'");
		}
		if(nationality!=null&&!nationality.equals("")) {
			whereSql.append(" and u.nationality='"+nationality+"'");
		}
		whereSql.append(" and t.states=2 and t.release=true");
		String orderStr="";
		if(score==2) {    //价格
			orderStr=" order by t.price";
		}
		try {
			List<Map<String, Object>> list=dao.selectTeacherList(whereSql.toString(), orderStr,(pageIndex-1)*size,size);
			List<Map<String, Object>> list1=new ArrayList<>();
			for(Map<String, Object> map:list) {
				Double longitude1=Double.valueOf(map.get("longitude").toString());
				Double latitude1=Double.valueOf(map.get("latitude").toString());
				Double ju=LocationUtils.getDistance(latitude, longitude, latitude1, longitude1);
				map.put("ju", ju);
				Integer userId=Integer.valueOf(map.get("userid").toString());
				Double fen=tDao.selectAvgScore(userId);
				map.put("fen", fen);
				list1.add(map);
			}
			if(score==3) {    //距离
				
				 Collections.sort(list1, new Comparator<Map<String, Object>>() {
			            public int compare(Map<String, Object> o1, Map<String, Object> o2) {
			            	Double name1 = Double.parseDouble(o1.get("ju").toString()) ;//name1是从你list里面拿出来的一个 
			            	Double name2 = Double.parseDouble(o2.get("ju").toString()) ; //name1是从你list里面拿出来的第二个name
			                return name1.compareTo(name2);
			            }
			        });
			}
			if(score==1) {
				
				 Collections.sort(list1, new Comparator<Map<String, Object>>() {
			            public int compare(Map<String, Object> o1, Map<String, Object> o2) {
			            	Double name1 = Double.parseDouble(o1.get("fen").toString()) ;//name1是从你list里面拿出来的一个 
			            	Double name2 = Double.parseDouble(o2.get("fen").toString()) ; //name1是从你list里面拿出来的第二个name
			                return name2.compareTo(name1);
			            }
			        });
			}
			return new ResultBean<>(list1);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return new ResultBean<>(e);
		}
	}

	@Override
	public ResultBean<Map<String, Object>> selectByTeacherId(int id,int userid) {
		// TODO Auto-generated method stub
		Map<String, Object> map=new HashMap<>();
		try {
			Teacher tea=dao.selectById(id);
			User user=uDao.selectById(tea.getUserid());
			TeacherAuthentication ta=tDao.getByUserid(tea.getUserid());
			map.put("TeacherAuthentication", ta);
			if(ta!=null) {
				int age=0;
				if(ta.getBirthdate()!=null&&!ta.getBirthdate().equals("")) {
					SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
				    Date bithday = format.parse(ta.getBirthdate());
					age=DataUtil.getAgeByBirth(bithday);
				}
				map.put("nianling", age);
				List<Map<String, Object>> la=aclDao.selectByAuthenticationid(ta.getId(),1);
				map.put("lanuage", la);
				map.put("certificate", acfDao.selectByAuthenticationid(ta.getId(),1));
				map.put("school", acsDao.selectByAuthenticationid(ta.getId(),1));
				map.put("studying", asDao.selectByAuthenticationid(ta.getId(),1));
				map.put("credit", tacDao.selectByAuthenticationid(ta.getId()));
				Integer jiao=acDao.selectStates(user.getId());
				if(jiao!=null) {
					if(jiao==1) {
						map.put("isJiao", true);
					}
				}else {
					map.put("isJiao", false);
				}
				List<Collect> list=cDao.selectList(new EntityWrapper<Collect>().eq("userid", userid).and().eq("collecttype", 1).and().eq("collectid", id));
				if(list.size()>0) {
					map.put("isCollect", true);
				}else {
					map.put("isCollect", false);
				}
			}
			Double fen=tDao.selectAvgScore(user.getId());
			map.put("fen", fen);
			int fuNum=toDao.selectOrderCountByTeacherId(id);
			map.put("fuNum", fuNum);
			map.put("teacher", tea);
			map.put("user", user);
			return new ResultBean<>(map);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return new ResultBean<>(e);
		}
	}

	@Override
	public ResultBean<List<Map<String, Object>>> findHotTeachers() {
		// TODO Auto-generated method stub
		List<Map<String,Object>> interpreterList= dao.selectByTop();
		return  new ResultBean<>(interpreterList);
	}

	@Override
	public ResultBean<Integer> selectByTeacherCount(Teacher tea, String ages, String teachings, Double minprice,
			Double maxprice, String nationality, String keyword) {
		// TODO Auto-generated method stub
		StringBuffer whereSql=new StringBuffer(" where 1=1 and t.name like '%"+keyword+"%'");
		if(tea.getLanguageid()!=null&&tea.getLanguageid()!=0) {
			whereSql.append(" and t.languageid="+tea.getLanguageid());
		}
		if(minprice!=null&&minprice!=0.0) {
			whereSql.append(" and t.price>="+minprice+" and t.price<="+maxprice);
		}
		if(ages!=null&&!ages.equals("")) {
			String[] age=ages.split("-");
			whereSql.append(" and u.age>="+age[0]+" and u.age<="+age[1]);
		}
		if(teachings!=null&&!teachings.equals("")) {
			String[] teaching=teachings.split("-");
			whereSql.append(" and t.teaching>="+teaching[0]+" and t.teaching<="+teaching[1]);
		}
		if(tea.getPrice()!=null&&tea.getPrice()!=0) {
			whereSql.append(" and i.intolanguage="+tea.getPrice());
		}
		if(tea.getLanguagegrade()!=null&&!tea.getLanguagegrade().equals("")) {
			whereSql.append(" and t.languagegrade='"+tea.getLanguagegrade()+"'");
		}
		if(tea.getAddress()!=null&&!tea.getAddress().equals("")) {
			whereSql.append(" and t.address like '%"+tea.getAddress()+"%'");
		}
		if(tea.getHauptstudiumid()!=null&&!tea.getHauptstudiumid().equals("")) {
			whereSql.append(" and t.hauptstudiumid='"+tea.getHauptstudiumid()+"'");
		}
		if(tea.getExperience()!=null&&!tea.getExperience().equals("")) {
			whereSql.append(" and t.experience="+tea.getExperience());
		}
		if(tea.getEducation()!=null&&!tea.getEducation().equals("")) {
			whereSql.append(" and t.education='"+tea.getEducation()+"'");
		}
		if(tea.getCertificate()!=null&&!tea.getCertificate().equals("")) {
			whereSql.append(" and t.certificate='"+tea.getCertificate()+"'");
		}
		if(nationality!=null&&!nationality.equals("")) {
			whereSql.append(" and u.nationality='"+nationality+"'");
		}
		whereSql.append(" and t.states=2 and t.release=true");
		int count=dao.selectTeacherListCount(whereSql.toString());
		return new ResultBean<Integer>(count);
	}

}
